package com.snda.sc.utils;

import java.io.File;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.springframework.util.DigestUtils;

public abstract class CommonUtils {

	public static String md5(String content) {
		return md5(content, "UTF-8");
	}

	public static String md5(String content, String charset) {
		return md5(content.getBytes(Charset.forName(charset)));
	}

	public static String md5(byte[] content) {
		return DigestUtils.md5DigestAsHex(content);
	}

	public static String formatTime(long timestamp, String pattern) {
		SimpleDateFormat fmt = new SimpleDateFormat(pattern, Locale.SIMPLIFIED_CHINESE);
		Date date = new Date(timestamp);
		return fmt.format(date);
	}

	public static String formatTime(long timestamp) {
		return formatTime(timestamp, "yyyy-MM-dd HH:mm:ss");
	}

	public static String formatTime() {
		return formatTime(System.currentTimeMillis());
	}

	public static ClassLoader getDefaultClassLoader() {
		ClassLoader cl = null;
		try {
			cl = Thread.currentThread().getContextClassLoader();
		} catch (Exception e) {
		}
		if (cl == null) {
			cl = CommonUtils.class.getClassLoader();
		}
		return cl;
	}

	public static File getFileByClassLoader(String name) {
		URL url = getDefaultClassLoader().getResource(name);
		if (url == null) return null;
		try {
			return new File(url.toURI());
		} catch (URISyntaxException e) {
			return null;
		}
	}

	public static InputStream getStreamByClassLoader(String name) {
		InputStream is = getDefaultClassLoader().getResourceAsStream(name);
		return is;
	}

	public static boolean isNumber(String str) {
		if (isEmpty(str)) return false;
		return str.matches("\\-?\\d+");
	}

	public static boolean isEmpty(CharSequence cs) {
		return cs == null || cs.length() <= 0;
	}

	public static boolean isFile(File file) {
		return file.exists() && file.isFile();
	}

	public static <K, V> Map<K, V> initMap(K key, V value) {
		Map<K, V> map = new HashMap<>();
		map.put(key, value);
		return map;
	}

	public static String uuid() {
		String uuid = UUID.randomUUID().toString();
		return uuid.replaceAll("-", "");
	}

	public static <K, V> Map<K, V> initMap(K key1, V value1, K key2, V value2) {
		Map<K, V> map = new HashMap<>();
		map.put(key1, value1);
		map.put(key2, value2);
		return map;
	}

	@SuppressWarnings("unchecked")
	public static <T> Set<T> initSet(T... elms) {
		Set<T> set = new HashSet<>();
		for (T elm : elms)
			set.add(elm);
		return set;
	}
}
